package com.atguigu.gulimall.gulimalltestssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class loginController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        String s = redisTemplate.opsForValue().get(token);
        return s;
    };
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,@CookieValue(value = "sso_token",required = false) String sso_token){
        if (!StringUtils.isEmpty(sso_token)){
            //Cookie存在，说明已经登录过，直接重定向
            return "redirect:"+url+"?username=sb&token="+sso_token;
        }
        model.addAttribute("url",url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String UserName,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse httpServletResponse){
        if (!StringUtils.isEmpty(UserName)&&!StringUtils.isEmpty(password)){
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid,UserName);
            System.out.println(uuid);
            Cookie cookie = new Cookie("sso_token", uuid);
            httpServletResponse.addCookie(cookie);
            return "redirect:"+url+"?username=sb&token="+uuid;
        }else {
            System.out.println(1224);
            return "login";
        }
        // 失败

    }
}
